<!DOCTYPE HTML>
<html lang="">
<head>
    <!--Setting-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-transform">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta name="apple-mobile-web-app-capable" content="ACUPT">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    <meta name="browsermode" content="application">
    <meta name="screen-orientation" content="portrait">
    <meta name="theme-version" content="1.2.3">
    <meta name="root" content="/">
    <link rel="dns-prefetch" href="https://acupt.github.io">
    <!--SEO-->

    <meta name="keywords" content="spring,rabbitmq" />


    <meta name="description" content="springboot集成rabbitMQ发消息123456789@Resourceprivate RabbitTemplate rabbitTemplate;@Value("$&#123;my..." />



<meta name="robots" content="all" />
<meta name="google" content="all" />
<meta name="googlebot" content="all" />
<meta name="verify" content="all" />

    <!--Title-->


<title>spring rabbitmq 异常重试源码分析 | ACUPT</title>


    <link rel="alternate" href="/atom.xml" title="ACUPT" type="application/atom+xml">


    <link rel="icon" href="/favicon.ico">

    



<link rel="stylesheet" href="/css/bootstrap.min.css?rev=3.3.7">
<link rel="stylesheet" href="/css/font-awesome.min.css?rev=4.5.0">
<link rel="stylesheet" href="/css/style.css?rev=@@hash">




    
	<div class="hide">
		<script type="text/javascript">
			var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan class='cnzz_stat_icon_1263868967 hide' %3E%3Cscript%20src%3D%22https%3A%2F%2Fs95.cnzz.com%2Fz_stat.php%3Fweb_id%3D1272564536%22%3E%3C%2Fscript%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1263868967%26show%3Dpic1' type='text/javascript'%3E%3C/script%3E"));
		</script>
	</div>






    

</head>


<!--[if lte IE 8]>
<style>
    html{ font-size: 1em }
</style>
<![endif]-->
<!--[if lte IE 9]>
<div style="ie">你使用的浏览器版本过低，为了你更好的阅读体验，请更新浏览器的版本或者使用其他现代浏览器，比如Chrome、Firefox、Safari等。</div>
<![endif]-->

<body>
    <header class="main-header"  style="background-image:url(http://snippet.shenliyang.com/img/banner.jpg)"  >
    <div class="main-header-box">
        <a class="header-avatar" href="/" title='ACUPT'>
            <img src="/img/avatar.jpg" alt="logo头像" class="img-responsive center-block">
        </a>
        <div class="branding">
        	<!--<h2 class="text-hide">Snippet主题,从未如此简单有趣</h2>-->
            
                 <img src="/img/branding.png" alt="Snippet 博客主题" class="img-responsive center-block">
            
    	</div>
    </div>
</header>
    <nav class="main-navigation">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="navbar-header"><span class="nav-toggle-button collapsed pull-right" data-toggle="collapse" data-target="#main-menu" id="mnav">
                    <span class="sr-only"></span>
                        <i class="fa fa-bars"></i>
                    </span>
                    <a class="navbar-brand" href="https://acupt.github.io">ACUPT</a>
                </div>
                <div class="collapse navbar-collapse" id="main-menu">
                    <ul class="menu">
                        
                            <li role="presentation" class="text-center">
                                <a href="/"><i class="fa "></i>Home</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="/categories/前端/"><i class="fa "></i>前端</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="/categories/后端/"><i class="fa "></i>后端</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="/categories/工具/"><i class="fa "></i>工具</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="/archives/"><i class="fa "></i>时间轴</a>
                            </li>
                        
                    </ul>
                </div>
            </div>
        </div>
    </div>
</nav>
    <section class="content-wrap">
        <div class="container">
            <div class="row">
                <main class="col-md-8 main-content m-post">
                    <p id="process"></p>
<article class="post">
    <div class="post-head">
        <h1 id="spring rabbitmq 异常重试源码分析">
            
	            spring rabbitmq 异常重试源码分析
            
        </h1>
        <div class="post-meta">
    
        <span class="categories-meta fa-wrap">
            <i class="fa fa-folder-open-o"></i>
            <a class="category-link" href="/categories/spring/">spring</a>
        </span>
    

    
        <span class="fa-wrap">
            <i class="fa fa-tags"></i>
            <span class="tags-meta">
                
                    <a class="tag-link" href="/tags/rabbitmq/">rabbitmq</a> <a class="tag-link" href="/tags/spring/">spring</a>
                
            </span>
        </span>
    

    
        
        <span class="fa-wrap">
            <i class="fa fa-clock-o"></i>
            <span class="date-meta">2018/11/15</span>
        </span>
        
    
</div>
            
            
    </div>
    
    <div class="post-body post-content">
        <h2 id="springboot集成rabbitMQ"><a href="#springboot集成rabbitMQ" class="headerlink" title="springboot集成rabbitMQ"></a>springboot集成rabbitMQ</h2><h3 id="发消息"><a href="#发消息" class="headerlink" title="发消息"></a>发消息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Resource</span></span><br><span class="line"><span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Value</span>(<span class="string">"$&#123;my.exchange&#125;"</span>)</span><br><span class="line"><span class="keyword">private</span> String exchange;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">send</span><span class="params">(Object obj)</span> </span>&#123;</span><br><span class="line">    rabbitTemplate.convertAndSend(exchange, <span class="string">""</span>, JsonUtils.toJson(obj));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="处理消息"><a href="#处理消息" class="headerlink" title="处理消息"></a>处理消息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RabbitListener</span>(queues = <span class="string">"$&#123;msg.queue.my.exchange&#125;"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">receive</span><span class="params">(String msg)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>默认情况下，如果处理消息时抛出了异常，这个消息会一直重复消费（重复调用receive方法），直到没有抛异常。</p>
<h2 id="消息接收-处理流程分析"><a href="#消息接收-处理流程分析" class="headerlink" title="消息接收/处理流程分析"></a>消息接收/处理流程分析</h2><p>在@RabbitListener注解的方法里打个断点，观察下调用栈。</p>
<p><img src="/img/spring/rabbitmq-listener-debug.jpg" alt=""></p>
<p>末端是个实现了Runnable的内部类SimpleMessageListenerContainer$AsyncMessageProcessingConsumer</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//……</span></span><br><span class="line">    <span class="comment">//从这里可以看出只要这个消费者（consumer）状态满足会一直轮询去接收消息和消费消息</span></span><br><span class="line">    <span class="keyword">while</span> (isActive(<span class="keyword">this</span>.consumer) || <span class="keyword">this</span>.consumer.hasDelivery() || !<span class="keyword">this</span>.consumer.cancelled()) &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">  	<span class="keyword">boolean</span> receivedOk = receiveAndExecute(<span class="keyword">this</span>.consumer); <span class="comment">// At least one message received</span></span><br><span class="line">   <span class="comment">//……</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//……</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">doReceiveAndExecute</span><span class="params">(BlockingQueueConsumer consumer)</span> <span class="keyword">throws</span> Throwable </span>&#123; <span class="comment">//NOSONAR</span></span><br><span class="line">	Channel channel = consumer.getChannel();</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="keyword">this</span>.txSize; i++) &#123;</span><br><span class="line">		logger.trace(<span class="string">"Waiting for message from consumer."</span>);</span><br><span class="line">		Message message = consumer.nextMessage(<span class="keyword">this</span>.receiveTimeout);</span><br><span class="line">		<span class="keyword">if</span> (message == <span class="keyword">null</span>) &#123;<span class="keyword">break</span>;&#125;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">//如果获取到了消息就会去消费，这里最终会执行到我们写的listener方法</span></span><br><span class="line">			executeListener(channel, message);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//当我们写的方法抛异常的时候就会来到这里</span></span><br><span class="line">		<span class="comment">//发现嫌疑代码：consumer.rollbackOnExceptionIfNecessary(ex)</span></span><br><span class="line">		<span class="keyword">catch</span> (ImmediateAcknowledgeAmqpException e) &#123;<span class="comment">/*……*/</span>&#125;</span><br><span class="line">		<span class="keyword">catch</span> (Throwable ex) &#123; <span class="comment">//NOSONAR</span></span><br><span class="line">			<span class="keyword">if</span> (causeChainHasImmediateAcknowledgeAmqpException(ex)) &#123;<span class="comment">/*……*/</span>&#125;</span><br><span class="line">			<span class="keyword">if</span> (<span class="keyword">this</span>.transactionManager != <span class="keyword">null</span>) &#123;<span class="comment">/*没开事务，忽略*/</span>&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				consumer.rollbackOnExceptionIfNecessary(ex);</span><br><span class="line">				<span class="keyword">throw</span> ex;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> consumer.commitIfNecessary(isChannelLocallyTransacted(channel));</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rollbackOnExceptionIfNecessary</span><span class="params">(Throwable ex)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">	<span class="keyword">boolean</span> ackRequired = !<span class="keyword">this</span>.acknowledgeMode.isAutoAck() &amp;&amp; !<span class="keyword">this</span>.acknowledgeMode.isManual();</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.transactional) &#123;<span class="comment">/*……*/</span>&#125;</span><br><span class="line">		<span class="keyword">if</span> (ackRequired) &#123;</span><br><span class="line">			<span class="keyword">boolean</span> shouldRequeue = RabbitUtils.shouldRequeue(<span class="keyword">this</span>.defaultRequeuRejected, ex, logger);</span><br><span class="line">			<span class="keyword">for</span> (Long deliveryTag : <span class="keyword">this</span>.deliveryTags) &#123;</span><br><span class="line">				<span class="comment">// 最终会执行到这里</span></span><br><span class="line">				<span class="comment">// With newer RabbitMQ brokers could use basicNack here...</span></span><br><span class="line">				<span class="keyword">this</span>.channel.basicReject(deliveryTag, shouldRequeue);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (<span class="keyword">this</span>.transactional) &#123;<span class="comment">/*……*/</span>&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		logger.error(<span class="string">"Application exception overridden by rollback exception"</span>, ex);</span><br><span class="line">		<span class="keyword">throw</span> e;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">finally</span> &#123;</span><br><span class="line">		<span class="keyword">this</span>.deliveryTags.clear();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由上可看出，导致无限重试的两个值：</p>
<ul>
<li>ackRequired: 和ack模式相关</li>
<li>shouldRequeue: 和defaultRequeuRejected以及抛出的异常类型有关</li>
</ul>
<p>根据需要修改acknowledgeMode或者defaultRequeuRejected即可，在配置文件中根据IDE补全提示可以找到这两个属性。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">spring.rabbitmq.listener.acknowledge-mode=none</span><br><span class="line">spring.rabbitmq.listener.default-requeue-rejected=false</span><br></pre></td></tr></table></figure>
<p>如果只是不想异常时重试，直接在业务代码中try…catch全部代码不让抛异常也行。</p>
<p>PS：验证这两个配置的时候发现不生效，一番debug发现项目里面自定义了一个工厂bean，创建消费者相关对象时用的那个工厂bean，而不是根据配置属性生成。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> SimpleRabbitListenerContainerFactory <span class="title">rabbitListenerContainerFactory</span><span class="params">(ConnectionFactory connectionFactory)</span> </span>&#123;</span><br><span class="line">    SimpleRabbitListenerContainerFactory factory = <span class="keyword">new</span> SimpleRabbitListenerContainerFactory();</span><br><span class="line">    factory.setConnectionFactory(connectionFactory);</span><br><span class="line">    factory.setMessageConverter(<span class="keyword">new</span> Jackson2JsonMessageConverter());</span><br><span class="line">    <span class="keyword">return</span> factory;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注释掉这个bean那两个配置才生效，当然也可以在这个bean里设置那两个属性。</p>

    </div>
    
    <div class="post-footer">
        <div>
            
                转载声明：商业转载请联系作者获得授权,非商业转载请注明出处 © <a href="" target="_blank">Snippet</a>
            
        </div>
        <div>
            
        </div>
    </div>
</article>

<div class="article-nav prev-next-wrap clearfix">
    
        <a href="/2018/11/20/thrift-start/" class="pre-post btn btn-default" title='thrift-Java 示例'>
            <i class="fa fa-angle-left fa-fw"></i><span class="hidden-lg">上一篇</span>
            <span class="hidden-xs">thrift-Java 示例</span>
        </a>
    
    
        <a href="/2018/10/29/spring-cloud-source-diy/" class="next-post btn btn-default" title='spring cloud 自定义配置源及配置刷新'>
            <span class="hidden-lg">下一篇</span>
            <span class="hidden-xs">spring cloud 自定义配置源及配置刷新</span><i class="fa fa-angle-right fa-fw"></i>
        </a>
    
</div>


    <div id="comments">
        
	
    <div id="vcomments" class="valine"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="/assets/valine.min.js"></script>

    <script>
        new Valine({
            av: AV,
            el: '#vcomments',
            appId: 'xOKV9J4UeQAtVkvnJC7Kq2Jn-gzGzoHsz',
            appKey: 'erIpQac4azoCmgfBB7Dl9maa',
            placeholder: '说点什么吧',
            notify: false,
            verify: true,
            avatar: 'mm',
            meta: 'nick,mail'.split(','),
            pageSize: '10',
            path: window.location.pathname,
            lang: ''.toLowerCase()
        })
    </script>


    </div>





                </main>
                
                    <aside id="article-toc" role="navigation" class="col-md-4">
    <div class="widget">
        <h3 class="title">Table of Contents</h3>
        
            <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#springboot集成rabbitMQ"><span class="toc-text">springboot集成rabbitMQ</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#发消息"><span class="toc-text">发消息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#处理消息"><span class="toc-text">处理消息</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#消息接收-处理流程分析"><span class="toc-text">消息接收/处理流程分析</span></a></li></ol>
        
    </div>
</aside>

                
            </div>
        </div>
    </section>
    <footer class="main-footer">
    <div class="container">
        <div class="row">
        </div>
    </div>
</footer>

<a id="back-to-top" class="icon-btn hide">
	<i class="fa fa-chevron-up"></i>
</a>




    <div class="copyright">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="busuanzi">
    
</div>

            </div>
            <div class="col-sm-12">
                <span>Copyright &copy; 2017
                </span> |
                <span>
                    Powered by <a href="//hexo.io" class="copyright-links" target="_blank" rel="nofollow">Hexo</a>
                </span> |
                <span>
                    Theme by <a href="//github.com/shenliyang/hexo-theme-snippet.git" class="copyright-links" target="_blank" rel="nofollow">Snippet</a>
                </span>
            </div>
        </div>
    </div>
</div>







<script src="/js/app.js?rev=@@hash"></script>

</body>
</html>